﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Markup;

namespace GoodStuff.Silverlight
{
    public static class DynamicTemplate
    {
        private static readonly DataTemplate _defaultTemplate = (DataTemplate)XamlReader.Load(
                   "<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
                                  "xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " +
                                  "xmlns:vm='clr-namespace:GoodStuff.Silverlight;assembly=GoodStuff.Silverlight'> " +
                       "<ContentControl vm:DynamicTemplate.Model=\"{Binding}\" HorizontalContentAlignment=\"Stretch\" />" +
                   "</DataTemplate>"
                   );

        public static DependencyProperty ModelProperty =
            DependencyProperty.RegisterAttached(
                "Model",
                typeof(object),
                typeof(DynamicTemplate),
                new PropertyMetadata(ModelChanged)
                );

        public static void SetModel(DependencyObject d, object value)
        {
            d.SetValue(ModelProperty, value);
        }

        public static object GetModel(DependencyObject d)
        {
            return d.GetValue(ModelProperty);
        }

        public static void ModelChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue == args.OldValue)
            {
                return;
            }
            if (args.NewValue == null)
            {
                //clear existing content.
                ((ContentControl)sender).Content = null;
                return;
            }

            ViewModelBase viewModel = args.NewValue as ViewModelBase;

            var view = ViewLocator.Locate(viewModel);
            ViewModelBinder.Bind(viewModel, view);

            ((ContentControl)sender).Content = view;
        }

        public static DataTemplate GetDynamicTemplate()
        {
            return _defaultTemplate;
        }
    }
}
